<script setup lang="ts">
import { createOrderIdAPI, getPatientInfoAPI, getPreConsultOrderAPI } from '@/apis/consult';
import router from '@/router';
import { useConsultStore } from '@/stores';
import type { ConsultOrderPreData, PartialConsult } from '@/types/consult';
import type { getPatirntType } from '@/types/user';
import { showConfirmDialog, showDialog, showToast } from 'vant';
import { onMounted, ref } from 'vue';
import { onBeforeRouteLeave } from 'vue-router';

defineOptions({
  name: 'consult-pay'
})

// 定义响应式数据 保存预支付
const preOrderInfo = ref<ConsultOrderPreData>()

// 响应式数据 保存患者的信息
const patientInfo = ref<getPatirntType>()

const store = useConsultStore()
// 定义函数 获取预支付的数据
const getPreOrderInfo = async () => {
  const res = await getPreConsultOrderAPI({
    // 从store里面拿到 type 和 illnessType
    type: store.consult.type,
    illnessType: store.consult.illnessType
  })
  // console.log(res)
  preOrderInfo.value = res.data
  // 收集优惠卷id
  store.setCouponId(preOrderInfo.value.couponId)
}

const getPatientInfo = async () => {
  if (!store.consult.patientId) return
  const res = await getPatientInfoAPI(store.consult.patientId)
  // console.log(res,111)
  patientInfo.value = res.data
}

type key = keyof PartialConsult

onMounted(() => {
  // 定义一个数组数组里面保存 填写的记录的字段名
  const keyArr: key[] = [
    'type',
    'consultFlag',
    'illnessDesc',
    'illnessTime',
    'depId',
    'patientId',
    'illnessType'
  ]
  const isValue = keyArr.every((item) => store.consult[item] !== undefined)
  if (!isValue) {
    return showDialog({
      title: '温馨提示',
      message:
        '问诊信息不完整请重新填写，如有未支付的问诊订单可在问诊记录中继续支付',
      closeOnPopstate: false
    }).then(() => {
      // 跳转到首页
      router.push('/')
    })
  }
  getPreOrderInfo()
  getPatientInfo()
})
// 同意选项
const isAgree = ref(false)

// 控制抽屉的显示
const isShow = ref(false)


// 保存订单id
const orderId = ref<string>('')

// 加载效果
const loading = ref(false)

const onSubmit = async () => {
  // 如果没有勾选我同意 就提示用户
  if (!isAgree.value) return showToast('请勾选我已同意支付协议')
  // 显示抽屉
  loading.value = true
  // 发送请求生成订单
  const res = await createOrderIdAPI(store.consult)
  // console.log(res)
  // 保存订单id
  orderId.value = res.data.id
  // 关闭加载效果
  loading.value = false
  // 清空数据
  store.clear()
  // 打开抽屉
  isShow.value = true
}
// 阻止返回上一页
onBeforeRouteLeave(() => {
  // 如果有订单id就不让页面回退
  if (orderId.value) return false
})
// before-close	关闭前的回调函数，返回 false 可阻止关闭，支持返回 Promise
const onClose = () => {
  return showConfirmDialog({
    title: '温馨提示',
    message:
      '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    // 确认按钮文案
    confirmButtonText: '继续支付',
    // 取消按钮文案
    cancelButtonText: '仍要关闭'
  })
    .then(() => {
      // on confirm
      return false
    })
    .catch(() => {
      // on cancel
      // 清空订单id 让用户可以回退页面
      orderId.value = ''
      // 让其跳转到问诊记录
      router.push('/user/consult')
      // 关闭动作面板
      return true
    });
}


</script>

<template>
  <div class="consult-pay-page" v-if="preOrderInfo && patientInfo">
    <cp-nav-bar title="支付" />
    <div class="pay-info">
      <p class="tit">图文问诊 {{ preOrderInfo?.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${preOrderInfo?.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${preOrderInfo?.pointDeduction}`" />
      <van-cell title="实付款" :value="`-¥${preOrderInfo?.actualPayment}`" class="pay-price" />
    </van-cell-group>
    <div class="pay-space"></div>
    <van-cell-group>
      <van-cell title="患者信息"
        :value="`${patientInfo?.name} | ${patientInfo?.genderValue} | ${patientInfo?.age}岁`"></van-cell>
      <van-cell title="病情描述" :label="store.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="isAgree">我已同意 <span class="text">支付协议</span></van-checkbox>
    </div>
    <van-submit-bar button-type="primary" :price="preOrderInfo?.actualPayment * 100" button-text="立即支付"
      text-align="left" @click="onSubmit" :loading="loading" />
    <!-- closeable	是否显示关闭图标 -->
    <!-- close-on-popstate	是否在页面回退时自动关闭 -->
    <!-- 显示抽屉组件 -->
    <cp-pay-sheet v-model:isShow="isShow" :onClose="onClose" :order-id="orderId"
      :actualPayment="preOrderInfo.actualPayment" pay-callback="/room"></cp-pay-sheet>
  </div>
  <!-- 骨架屏 -->
  <div class="consult-pay-page" v-else>
    <cp-nav-bar title="支付" />
    <van-skeleton title :row="15" style="margin-top: 20px" />
  </div>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
}

.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;

  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }

  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }

  .desc {
    flex: 1;

    >span {
      display: block;
      color: var(--cp-tag);

      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}

.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }

    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}

.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}

.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;

  .text {
    color: var(--cp-primary);
  }
}

::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}
</style>